import parseAttrsString from "./parseAttrsString"
export default function parse (templateStr) {
    let index = 0
    let rest = ''
    let stack1 = []
    let stack2 = [{'children': []}]
    while (index < templateStr.length - 1) {
        // console.log(templateStr[index])
        // 识别遍历到得字符，是不是开始标签
        rest = templateStr.substring(index)
        const startRegExp = /^\<([a-z]+[1-6]?)(\s[^\<]+)?\>/
        const endRegExp = /^\/([a-z]+[1-6]?)\>/
        const textRegExp = /^([^\<]+)\<\/[a-z]+[1-6]?\>/
        if (startRegExp.test(rest)) {
            let tag = rest.match(startRegExp)[1]
            let attrsString = rest.match(startRegExp)[2]
            // console.log('监测到开始标记',tag)
            stack1.push(tag)
            stack2.push({
                tag: tag,
                children: [],
                attrs: parseAttrsString(attrsString)
            })
            const attrsStrLeng = attrsString ? attrsString.length : 0
            index += tag.length + 2 + attrsStrLeng // (<>有两位)
        } else if (endRegExp.test(rest)) {
            let tag = rest.match(endRegExp)[1]
            // console.log('监测到结束标记',tag)
            let pop_tag = stack1.pop() 
            if (tag == pop_tag) {
                let pop_arr = stack2.pop()
                if (stack2.length > 0) {
                    stack2[stack2.length - 1].children.push(pop_arr)
                }
            } else {
                throw new Error('标签未闭合')
            }
            index += tag.length + 3 // (</>有3位)
        } else if (textRegExp.test(rest)) {
            let text = rest.match(textRegExp)[1]
            if (!/^\s+$/.test(text)) {
                // console.log('监测到文字',text)
                if (stack2.length > 0) {
                    stack2[stack2.length - 1].children.push({'text': text, type: 3})
                }
            }
            index += text.length
        } else {
            index++
        }
    }
    console.log(stack2[0].children[0])
    return stack2[0].children[0]
}